// pages/tips/tips.js
var util = require('../../utils/util.js');  
var api = require('../../config/api.js'); 
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;
var qnaire;//
var len;
var ans;  //答案数组初始化，会在onload函数中赋初值""
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dates: util.formatTime(new Date()),
    qnaire: qnaire,
    answer: ans,
    id: 0,
    province:'',
    city:'',
    addr:'',
    tag:['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'],
    tagAnc: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'i', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  },

  showDetail:function(e){
    wx.showModal({
      title: '详细题目',
      content: qnaire[parseInt(e.currentTarget.dataset.value)].question,
      success: function (res) {
        
      },
      fail:function(e){
        wx.showToast({
          title: '错误',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  //  点击日期组件确定事件  
  bindDateChange: function (e) {
    console.log(e.detail.value)
    this.setData({
      dates: e.detail.value
    })
  },
  //单选
  radioChange: function (e) {
    console.log(e.detail.value)
  },
  //多选
  checkboxChange: function (e) {
    console.log(e.detail.value)
  },
  //下一个
nextq: function () {
    if (this.data.id < len-1) {
      this.setData({
        id: this.data.id + 1,
      })
    }
  },
 //前一个
lastq: function (e) {
    if (this.data.id != 0) {
      this.setData({
        id: this.data.id - 1,
      })
    }
  },
 //提交
submit: function (e) {
    console.log(e.detail.value);
    var a = e.detail.value.answer;
    var id = this.data.id;
    ans[id] = a;
    this.setData({
      answer: ans,
    })
  console.log(this.data.id,"---",this.data.answer);

  },

//判断答题完成情况
formSubmit: function () {
    var finish;
    var i = 0;
    var _this = this;
    while (i < len) {
      if (qnaire[i].ifMust == 0){
        finish = 'true';
      }
      //Object.keys(ans[i]).length === 0 用来判断对象长度的
      else if (ans[i] == "") {
        finish = 'false';
        break;
      } else {
        finish = 'true';
      }
      i++;
    }
    if (finish == 'false') {
      wx.showModal({
        title: '无法提交',
        content: '您还有部分题目未完成，请检查后重新提交',
        showCancel: false,
        confirmColor: '#fcbe39',
        confirmText: "好的",
        success(res) {
          _this.setData({
            id: i,
          })
        }
      })
    } else {
      wx.showLoading({
        title: '加载中',
      })
      wx.request({
        url: api.Question_UPDATE_URL,
        method: 'POST',
        dataType: 'json',
        data: { 
          answer : ans
        },
        header: { 'content-type': 'application/json' },
        success: function (res) {
          wx.hideLoading()
          wx.showToast({
            title: '提交成功',
            icon: 'success',
            duration: 2000
          })
          setTimeout(function () {
            wx.navigateBack({
                delta: 1
            })
          },2000)
        },
        fail:function(res){
          wx.showToast({
            title: '提交失败',
            icon: 'none',
            duration: 2000
          })
        }
      })
      // setTimeout(function () {
      //   wx.hideLoading({
      //     success(res) {
      //       _this.answer2db();
            
      //       //返回上一个页面
      //       wx.navigateBack({
      //         delta: 1
      //       })
      //     }
      //   })
        
      // }, 2000)
    }
  },
  tip_info:function(){
    wx.showToast({
      title: '此题必须填写！',
      icon: 'none',
      duration: 1500
    })
  },
//将用户完成的答案数组上传至云数据库
answer2db: function () {
  for(var i=0;i<ans.length;i++){
    if (!ans[i]){
      ans[i]=""
    }
  }
  console.log("提交",ans)
  },
  //请求题目
  addQ_put: function () {
    var that = this;
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: api.Get_Question_URL,
      method: 'GET',
      dataType:'json',
      success: function (res) {
        wx.hideLoading()
        console.log(res)
        qnaire = res.data
        len = res.data.length
        ans = new Array(that.data.len)
        that.data.qnaire = res.data
        that.data.answer = ans
        that.setData({
          qnaire: qnaire,
          len: len,
          ans: ans,
          answer : ans
        })
      },
      fail: function (res) {
        wx.showToast({
          title: '获取问卷数据错误',
          icon: 'none',
          duration: 2000
        })
        setTimeout(function () {
          //返回上一个页面
          wx.navigateBack({
            delta: 1
          })
        }, 2000)
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'BHXBZ-LMAKK-KJ2JG-AJS4Q-43CLQ-4CFLY'
    });
    wx.getSetting({
      success: (res) => {
        console.log(JSON.stringify(res))
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //调用wx.getLocation的API  获取地址
          this.getLocation()
        }
        else {
          //调用wx.getLocation的API  获取地址
          this.getLocation()
        }
      }
    })
    this.addQ_put();
  },
  //获取位置信息
getLocation:function(){
  let vm = this;
  wx.getLocation({
    type:'wgs84',
    success: function(res) {
      console.log(res)
      var latitude = res.latitude
      var longitude = res.longitude
      var speed = res.speed
      var accuracy = res.accuracy
      vm.getLocal(latitude,longitude)
    },
    fail:function(res){
      wx.showToast({
        title: '获取位置信息失败',
        icon: 'error',
        duration: 1000
      })
    }
  })
},
  getLocal: function (latitude, longitude){
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location:{
        latitude: latitude,
        longitude: longitude
      },
      success:function(res){
        console.log(res)
        let province = res.result.ad_info.name
        let city = res.result.ad_info.city
        vm.setData({
          province:province,
          city:city,
        })
      }
    })
  },
  //更新地址
  updateAddress:function(){
    wx.showToast({
      title: '正在获取位置信息',
      icon: 'none',
      duration: 1000
    })
    this.getLocation()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})